<template>
  <el-main>
    <div class="mt-4">
      <el-row>
        <el-col :span="12">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <!-- <div style=""></div> -->
            <el-form-item>
              <el-select v-model="formInline.ifpay" placeholder="请选择状态" clearable>
                <el-option value="已支付" />
                <el-option value="未支付" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="getorderbyifpay">
                <el-icon><Search /></el-icon>筛选
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>
    </div>
    <el-row>
      <el-table :data="tableData" class="table" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="time" label="创建时间" width="180">
          <template #default="scope">
            <span>{{ scope.row.addtime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="water" label="用水量" width="100">
          <template #default="scope">
            <span>{{ scope.row.usedWater }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="water_price" label="水费" width="100">
          <template #default="scope">
            <span>{{ scope.row.waSum }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="electrical" label="用电量" width="100">
          <template #default="scope">
            <span>{{ scope.row.usedElc }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="electrical_price" label="电费" width="100">
          <template #default="scope">
            <span>{{ scope.row.elSum }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="账单金额" width="100">
          <template #default="scope">
            <span>{{ scope.row.sum }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="pay_status" label="是否支付" width="100">
          <template #default="scope">
            <el-tag :class="scope.row.ifpay === '已支付' ? 'success-pay' : 'danger-pay'">
              {{ scope.row.ifpay }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pay_time" label="截止日期" width="180">
          <template #default="scope">
            <span>{{ scope.row.endLine }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
              <el-icon ></el-icon>支付
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row class="center">
      <el-button mb-2 @click="toggle" class="tranlate">Switch Language</el-button>
      <br />
      <el-config-provider :locale="locale"> </el-config-provider>
    </el-row>

    <el-pagination class="pagination"
      background
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper"
    />
  </el-main>
</template>

<script lang="ts" setup>
import { ref, reactive} from "vue";
import { computed } from "vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import en from "element-plus/dist/locale/en.mjs";
import { onMounted } from "vue";
import axios from "axios";


const form = reactive({
  name: "",
  address: "",
  telephone: "",
});


const select = ref("");
const handleClick = () => {
  console.log("click");
};
const Search = ref("");
const language = ref("zh-cn");
const locale = computed(() => (language.value === "zh-cn" ? zhCn : en));
const toggle = () => {
  language.value = language.value === "zh-cn" ? "en" : "zh-cn";
};

const dialogVisible = ref(false);

const pageSize = ref(6); // 每页显示10条数据
const currentPage = ref(1);
const total = ref(0); // 总记录数

const tableData = ref<Orders[]>([]);
const getOrderbyuserid = () => {
  // 假设 localStorage 中存储了登录用户的 userid，键名为 'userInfo'从登录方法中获取uid
  const user = localStorage.getItem("user");
  const user2 = JSON.parse(user);
  const user_id = user2.userId;

  if (!user_id) {
    console.error("用户未登录或 userId 不存在");
    return;
  }
  const params = new URLSearchParams();
  params.append("user_id", user_id);
  // 使用 userId 发送请求到后端获取账单数据
  axios
    .get(`http://localhost:8080/orderInfo/selectorderbyuserid`, {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        user_id: user2.userId,
      },
    })
    .then((response) => {
      tableData.value = response.data.data.records;
      total.value = response.data.data.total;
    });
};

const getorderbyifpay = () => {
  // 假设 formInline.user 存储了客户姓名，formInline.region 存储了支付状态
  const ifPay = formInline.ifpay || '';
  const user = localStorage.getItem("user");
  const user2 = JSON.parse(user);
  const user_id = user2.userId;
  // 检查是否填支付状态

  const params = new URLSearchParams();
  params.append("user_id", user_id);
  params.append("ifpay", ifPay);

  // 发送请求到后端，查询符合条件的订单
  axios
    .get(`http://localhost:8080/orderInfo/selectorderbyifpay`, {
      params: {
        current: currentPage.value, // 使用 currentPage 变量作为当前页码
        size: pageSize.value,
        ifpay: formInline.ifpay,
        user_id: user2.userId,
      },
    })
    .then((response) => {
      tableData.value = response.data.data.records;
      total.value = response.data.data.total;
    });
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  // 重新获取当前页数据
  getorderbyifpay();
};
onMounted(() => {
  getOrderbyuserid();
  getorderbyifpay;
});
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
const activeIndex = ref("1");
const activeIndex2 = ref("1");
const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
interface Orders {
  addtime: string;
  ordId: string;
  realname: string;
  place: string;
  phone: string;
  usedWater: string;
  waSum: string;
  usedElc: string;
  elSum: string;
  sum: string;
  ifpay: "未支付" | "已支付";
  endLine: string;
  address: string;
  userId: string;
}

const handleEdit = async (index, row) => {
  // 检查订单是否已经支付
  if (row.ifpay === "已支付") {
    alert("该订单已支付！");
    return; // 退出函数
  }
  const user = localStorage.getItem("user");
  const user3 = JSON.parse(user);
  const user_id = user3.userId;
  const ord_id = row.ordId;
  // 弹出确认框询问用户是否确定要支付
  const params = new URLSearchParams();
  params.append("user_id", user_id);
  params.append("ord_id", ord_id);
  const confirmPay = window.confirm("您确定要支付吗？");

  if (confirmPay) {
    try {
      const response = await axios.get(
          `http://localhost:8080/orderInfo/checkBalance`,
          { params:
                { ord_id: row.ordId,
                  user_id: user3.userId,
                } }
      );

      if (response.data.data == true) {
        // 准备要发送到后端的数据
        const updatedOrder = {
          ...row, // 展开当前行的数据
          ifpay: "已支付", // 将支付状态改为“已支付”
        };

        // 发送 PUT 请求到后端更新订单状态
        const response = await axios.put(
            `http://localhost:8080/orderInfo/update`,
            updatedOrder
        );

        // 检查后端返回的结果
        if (response.data.code === 0) {
          // 更新表格数据的支付状态
          row.ifpay = "已支付";
          // 重新获取当前页数据以刷新显示
          getOrderbyuserid();
          console.log("支付状态更新成功");
        } else {
          console.error("支付状态更新失败:", response.data.message);
          alert("支付状态更新失败，请稍后重试！");
        }
      }
      else {
        alert("余额不足，请充值！");
      }
    } catch (error) {
      console.error("支付状态更新失败:", error);
      alert("支付状态更新失败，请稍后重试！");
    }
  }
};

const formInline = reactive({
  ifpay: "",
});

const onSubmit = () => {
  console.log("submit!");
};
</script>



<style>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.center {
  margin-top: 30px;
  margin-left: 300px;
}
.tranlate {
  display: none;
}
.table {
  width: 85%;
  margin-left: 50px;
  margin-top: 20px;
}
.success-pay {
  background-color: #67c23a;
  color: white;
}
.danger-pay {
  background-color: #f56c6c;
  color: white;
}
.pagination {
  text-align: center;
  margin-top: 20px;
  margin-left: 450px;
}
</style>
